﻿namespace MicroCloud.Filter
{
    /// <summary>
    /// 查询表达式服务
    /// </summary>
    public class FilterService : IFilterService
    {
        //字段
        #region "表达式字典字段"
        /// <summary>
        /// 表达式字典
        /// </summary>
        private static readonly Dictionary<FilterOperate, Func<Expression, Expression, Expression>> ExpressionDict =
            new()
            {
                {
                    FilterOperate.Equal,
                    Expression.Equal
                },
                {
                    FilterOperate.NotEqual,
                    Expression.NotEqual
                },
                {
                    FilterOperate.Less,
                    Expression.LessThan
                },
                {
                    FilterOperate.Greater,
                    Expression.GreaterThan
                },
                {
                    FilterOperate.LessOrEqual,
                    Expression.LessThanOrEqual
                },
                {
                    FilterOperate.GreaterOrEqual,
                    Expression.GreaterThanOrEqual
                },
                {
                    FilterOperate.StartsWith,
                    (left, right) =>
                    {
                        if (left.Type != typeof(string))
                        {
                            throw new NotSupportedException("“StartsWith”比较方式只支持字符串类型的数据");
                        }
                        return Expression.Call(left,
                            typeof(string).GetMethod("StartsWith", new[] { typeof(string) })
                            ?? throw new InvalidOperationException($"名称为“StartsWith”的方法不存在"),
                            right);
                    }
                },
                {
                    FilterOperate.EndsWith,
                    (left, right) =>
                    {
                        if (left.Type != typeof(string))
                        {
                            throw new NotSupportedException("“EndsWith”比较方式只支持字符串类型的数据");
                        }
                        return Expression.Call(left,
                            typeof(string).GetMethod("EndsWith", new[] { typeof(string) })
                            ?? throw new InvalidOperationException($"名称为“EndsWith”的方法不存在"),
                            right);
                    }
                },
                {
                    FilterOperate.Contains,
                    (left, right) =>
                    {
                        if (left.Type != typeof(string))
                        {
                            throw new NotSupportedException("“Contains”比较方式只支持字符串类型的数据");
                        }
                        return Expression.Call(left,
                            typeof(string).GetMethod("Contains", new[] { typeof(string) })
                            ?? throw new InvalidOperationException($"名称为“Contains”的方法不存在"),
                            right);
                    }
                },
                {
                    FilterOperate.NotContains,
                    (left, right) =>
                    {
                        if (left.Type != typeof(string))
                        {
                            throw new NotSupportedException("“NotContains”比较方式只支持字符串类型的数据");
                        }
                        return Expression.Not(Expression.Call(left,
                            typeof(string).GetMethod("Contains", new[] { typeof(string) })
                            ?? throw new InvalidOperationException($"名称为“Contains”的方法不存在"),
                            right));
                    }
                }
                //{
                //    FilterOperates.StdIn, (left, right) =>
                //    {
                //        if (!right.Type.IsArray)
                //        {
                //            return null;
                //        }
                //        return left.Type != typeof (string) ? null : Expression.Call(typeof (Enumerable), "Contains", new[] {left.Type}, right, left);
                //    }
                //},
                //{
                //    FilterOperates.DataTimeLessThanOrEqual, Expression.LessThanOrEqual
                //}
            };

        #endregion

        private readonly IServiceProvider _provider;

        #region "属性"
        #region "获取 当前用户"
        /// <summary>
        /// 获取 当前用户
        /// </summary>
        protected ClaimsPrincipal CurrentUser => _provider.GetCurrentUser();
        #endregion
        #region "获取 当前组织机构编号"
        /// <summary>
        /// 获取 当前组织机构编号
        /// </summary>
        protected string CurrentOrganizationId => _provider.GetCurrentOrganizationId();
        #endregion
        #region "获取 当前部门机构编号"
        /// <summary>
        /// 获取 当前部门机构编号
        /// </summary>
        protected string CurrentDepartmentId => _provider.GetCurrentDepartmentId();
        #endregion

        #region "获取 组织机构信息提供者"
        /// <summary>
        /// 获取 组织机构信息提供者
        /// </summary>
        protected IOrganizationProvider OrganizationProvider => _provider.GetService<IOrganizationProvider>();
        #endregion

        #region "获取 实体查询器"
        /// <summary>
        /// 获取 实体查询器
        /// </summary>
        protected IEntityQuerier EntityQuerier => _provider.GetService<IEntityQuerier>();
        #endregion

        /// <summary>
        /// 获取 实体信息处理器
        /// </summary>
        protected IEntityInfoHandler EntityInfoHandler => _provider.GetService<IEntityInfoHandler>();

        #endregion

        #region "构造函数"
        #region "初始化一个 <see cref="FilterService"/> 类型的新实例"
        /// <summary>
        /// 初始化一个 <see cref="FilterService"/> 类型的新实例
        /// </summary>
        /// <param name="provider">服务提供者</param>
        public FilterService(IServiceProvider provider)
        {
            _provider = provider;
        }
        #endregion

        #endregion

        #region "方法 - Implementation of IFilterService"
        #region "获取指定查询条件组的查询表达式"
        /// <summary>
        /// 获取指定查询条件组的查询表达式
        /// </summary>
        /// <typeparam name="T">表达式实体类型</typeparam>
        /// <param name="group">
        /// 查询条件组
        /// <para>如果为 null，则直接返回 true 表达式。</para>
        /// </param>
        /// <returns>查询表达式</returns>
        public virtual Expression<Func<T, bool>> GetExpression<T>(FilterGroup group)
        {
            Check.NotNull(group, nameof(group));

            ParameterExpression param = Expression.Parameter(typeof(T), "m");
            Expression body = GetExpressionBody(param, group);
            Expression<Func<T, bool>> expression = Expression.Lambda<Func<T, bool>>(body, param);
            return expression;
        }
        #endregion
        #region "获取指定查询条件的查询表达式"
        /// <summary>
        /// 获取指定查询条件的查询表达式
        /// </summary>
        /// <typeparam name="T">表达式实体类型</typeparam>
        /// <param name="rule">
        /// 查询条件
        /// <para>如果为 null，则直接返回 true 表达式。</para>
        /// </param>
        /// <returns>查询表达式</returns>
        public virtual Expression<Func<T, bool>> GetExpression<T>(FilterRule rule)
        {
            Check.NotNull(rule, nameof(rule));

            ParameterExpression param = Expression.Parameter(typeof(T), "m");
            Expression body = GetExpressionBody(param, rule);
            Expression<Func<T, bool>> expression = Expression.Lambda<Func<T, bool>>(body, param);
            return expression;
        }
        #endregion
        #region "获取指定查询条件组的查询表达式并综合数据权限"
        /// <summary>
        /// 获取指定查询条件组的查询表达式并综合数据权限
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="group">
        /// 传入的查询条件组
        /// <para>为空时则只返回数据权限过滤器</para>
        /// </param>
        /// <param name="operation">数据权限操作</param>
        /// <returns>综合之后的表达式</returns>
        public virtual Expression<Func<T, bool>> GetDataFilterExpression<T>(FilterGroup group = null, DataAuthOperation operation = DataAuthOperation.Read)
        {
            IDataAuthService dataAuthService = _provider.GetRequiredService<IDataAuthService>();
            Expression<Func<T, bool>> exp = dataAuthService.GetDataFilter<T>(operation, group);
            return exp;
        }
        #endregion
        #region "验证指定查询条件组是否能正常转换为表达式"
        /// <summary>
        /// 验证指定查询条件组是否能正常转换为表达式
        /// </summary>
        /// <param name="group">查询条件组</param>
        /// <param name="type">实体类型</param>
        /// <returns>验证操作结果</returns>
        public virtual OperationResult CheckFilterGroup(FilterGroup group, Type type)
        {
            try
            {
                ParameterExpression param = Expression.Parameter(type, "m");
                GetExpressionBody(param, group);
                return OperationResult.Success();
            }
            catch (System.Exception ex)
            {
                return OperationResult.Error(I18N.T("条件组验证失败：{0}", ex.Message));
            }
        }
        #endregion

        #endregion

        #region "受保护的方法"
        #region "获取表达式正文"
        /// <summary>
        /// 获取表达式正文
        /// </summary>
        /// <param name="param">表达式参数</param>
        /// <param name="group">筛选条件组</param>
        /// <returns></returns>
        protected virtual Expression GetExpressionBody(ParameterExpression param, FilterGroup group)
        {
            param.CheckNotNull(nameof(param));

            //如果无条件或条件为空，直接返回 true 表达式。
            if (group == null || (group.Rules.Count == 0 && group.Groups.Count == 0))
            {
                return Expression.Constant(true);
            }
            var filterGroup = group.Copy();
            filterGroup = BuildFilterGroup(filterGroup);
            List<Expression> bodies = new();
            bodies.AddRange(filterGroup.Rules.Select(rule => GetExpressionBody(param, rule)));
            bodies.AddRange(filterGroup.Groups.Select(subGroup => GetExpressionBody(param, subGroup)));

            if (filterGroup.Operate == FilterOperate.And)
            {
                return bodies.Aggregate(Expression.AndAlso);
            }
            if (filterGroup.Operate == FilterOperate.Or)
            {
                return bodies.Aggregate(Expression.OrElse);
            }
            throw new Exception(I18N.T(Resources.Filter_GroupOperateError));
        }
        #endregion
        #region "获取表达式正文"
        /// <summary>
        /// 获取表达式正文
        /// </summary>
        /// <param name="param">表达式参数</param>
        /// <param name="rule">筛选条件</param>
        /// <returns>表达式正文</returns>
        protected virtual Expression GetExpressionBody(ParameterExpression param, FilterRule rule)
        {
            // if (rule == null || rule.Value == null || string.IsNullOrEmpty(rule.Value.ToString()))
            if (rule == null)
            {
                return Expression.Constant(true);
            }
            LambdaExpression expression = default;
            #region "非外键关联实体查询逻辑"
            if (!rule.JoinEntityType.IsMissing() && EntityQuerier != null)
            {
                Check.NotNullOrEmpty(rule.JoinFilterField, nameof(rule.JoinFilterField));
                Check.NotNullOrEmpty(rule.JoinSelectField, nameof(rule.JoinSelectField));

                //------设置动态实体查询集
                var entityType = Type.GetType(rule.JoinEntityType) ?? throw new Exception(I18N.T("实体 {0} 不存在", rule.JoinEntityType));

                var entityQueryable = EntityQuerier.GetQueryable(entityType);
                //------设置筛选和提取规则
                var filterName = rule.JoinFilterField;
                FilterRule entityFilterRule = new(filterName, rule.Value, rule.Operate);
                var paramName = Guid.NewGuid().ToString();
                var whereExpression = GetExpressionBody(Expression.Parameter(entityType, paramName), entityFilterRule);
                var whereString = whereExpression.ToString().Replace($"{paramName}.", "");
                var selectField = rule.JoinSelectField;
                //------获取动态实体数据集
                entityQueryable = EntityQuerier.AddSelect(EntityQuerier.AddWhere(entityQueryable, whereString), selectField);
                //------构建新表达式树
                var propertyExpression = GetPropertyExpression(param, rule);  // x.name
                var entityValuesType = Array.CreateInstance(propertyExpression.Type, 0).GetType();
                var entityValues = entityQueryable.ToArray().ChangeType(entityValuesType);
                ConstantExpression value = Expression.Constant(entityValues, entityValuesType); // value 声明一个常量
                #region "示例备查"
                //------常规查询
                //BinaryExpression be = Expression.Equal(left, right); // x = >x.name == value
                //MethodInfo containsMethodString = typeof(string).GetMethod("Contains", new[] { typeof(string) }); // x = > x.Name.Contains("value")
                //var containsMethodExp = Expression.Call(left, containsMethod, right); // x = > x.Name.Contains("value")
                //------数组 包含查询
                //var test_arrays = new object[] { "11", "22", "33", "44", "55" };
                //var test_value = Expression.Constant(test_arrays, typeof(object[])); // value 声明一个常量
                //var test_property = Expression.Property(param, "Title");  // x.name
                //var test_containsMethod = typeof(Enumerable).GetMethods().FirstOrDefault(info => info.GetParameters().Length == 2 && info.Name == "Contains").MakeGenericMethod(typeof(object));
                //var test_contains = Expression.Call(null, test_containsMethod, test_value, test_property);//e.List.Contains("s")
                //var test_lambda = Expression.Lambda(test_contains, param);
                #endregion
                var containsMethod = typeof(Enumerable).GetMethods().FirstOrDefault(m => m.GetParameters().Length == 2 && m.Name == "Contains").MakeGenericMethod(propertyExpression.Type);
                //var containsMethod = typeof(Enumerable).GetMethods().Where(m => m.Name == "Contains").Single(m => m.GetParameters().Length == 2).MakeGenericMethod(propertyExpression.Type);
                var containsMethodExp = Expression.Call(null, containsMethod, value, propertyExpression);   // 扩展方法的调用需要通过一个null实例进行调用
                return containsMethodExp;
            }
            #endregion
            else
            {
                expression = GetPropertyLambdaExpression(param, rule);
            }

            if (expression == null)
            {
                return Expression.Constant(true);
            }
            Expression constant = ChangeTypeToExpression(param, rule, expression.Body.Type);
            var expressionBody = ExpressionDict[rule.Operate](expression.Body, constant);
            return expressionBody;
        }
        #endregion
        #region "获取属性表达式"
        /// <summary>
        /// 获取属性表达式
        /// </summary>
        /// <param name="param">表达式参数</param>
        /// <param name="rule">筛选条件</param>
        /// <returns>属性表达式</returns>
        protected virtual Expression GetPropertyExpression(ParameterExpression param, FilterRule rule)
        {
            string[] propertyNames = rule.Field.Split('.');
            if (rule.IsLowerCaseToUpperCase)
            {
                propertyNames = propertyNames.Select(m => m.ToUpperCase()).ToArray();
            }
            Expression propertyExpression = param;
            Type type = param.Type;
            for (var index = 0; index < propertyNames.Length; index++)
            {
                string propertyName = propertyNames[index];
                PropertyInfo property = type.GetProperty(propertyName);
                if (property == null)
                {
                    var errMsg = string.Format(I18N.T(Resources.Filter_RuleFieldInTypeNotFound), rule.Field, type.FullName);
                    throw new InvalidOperationException(errMsg);
                }
                type = property.PropertyType;

                propertyExpression = Expression.MakeMemberAccess(propertyExpression, property);
            }
            return propertyExpression;
        }
        #endregion
        #region "获取属性lambda表达式"
        /// <summary>
        /// 获取属性lambda表达式
        /// </summary>
        /// <param name="param">表达式参数</param>
        /// <param name="rule">筛选条件</param>
        /// <returns>属性lambda表达式</returns>
        protected virtual LambdaExpression GetPropertyLambdaExpression(ParameterExpression param, FilterRule rule)
        {
            string[] propertyNames = rule.Field.Split('.');
            if (rule.IsLowerCaseToUpperCase)
            {
                propertyNames = propertyNames.Select(m => m.ToUpperCase()).ToArray();
            }
            Expression propertyExpression = param;
            Type type = param.Type;
            for (var index = 0; index < propertyNames.Length; index++)
            {
                string propertyName = propertyNames[index];
                PropertyInfo property = type.GetProperty(propertyName);
                if (property == null)
                {
                    var errMsg = string.Format(I18N.T(Resources.Filter_RuleFieldInTypeNotFound), rule.Field, type.FullName);
                    throw new InvalidOperationException(errMsg);
                }
                type = property.PropertyType;

                //验证最后一个属性与属性值是否匹配
                if (index == propertyNames.Length - 1)
                {
                    bool flag = CheckFilterRule(type, rule);
                    if (!flag)
                    {
                        return null;
                    }
                }

                propertyExpression = Expression.MakeMemberAccess(propertyExpression, property);
            }
            return Expression.Lambda(propertyExpression, param);
        }
        #endregion
        #region "验证最后一个属性与属性值是否匹配"
        /// <summary>
        /// 验证最后一个属性与属性值是否匹配 
        /// </summary>
        /// <param name="type">最后一个属性</param>
        /// <param name="rule">条件信息</param>
        /// <returns>是否匹配</returns>
        protected virtual bool CheckFilterRule(Type type, FilterRule rule)
        {
            if (rule.Value == null || rule.Value.ToString() == string.Empty)
            {
                rule.Value = null;
            }

            if (rule.Value == null && (type == typeof(string) || type.IsNullableType()))
            {
                return rule.Operate == FilterOperate.Equal || rule.Operate == FilterOperate.NotEqual;
            }

            if (rule.Value == null)
            {
                return !type.IsValueType;
            }
            return true;
        }
        #endregion
        #region "将类型更改为表达式"
        /// <summary>
        /// 将类型更改为表达式
        /// </summary>
        /// <param name="param">表达式参数</param>
        /// <param name="rule">筛选条件</param>
        /// <param name="conversionType">转换类型</param>
        /// <returns>表达式正文</returns>
        /// <exception cref="Exception"></exception>
        protected virtual Expression ChangeTypeToExpression(ParameterExpression param, FilterRule rule, Type conversionType)
        {
            //if (item.Method == QueryMethod.StdIn)
            //{
            //    Array array = (item.Value as Array);
            //    List<Expression> expressionList = new List<Expression>();
            //    if (array != null)
            //    {
            //        expressionList.AddRange(array.Cast<object>().Select((t, i) =>
            //            ChangeType(array.GetValue(i), conversionType)).Select(newValue => Expression.Constant(newValue, conversionType)));
            //    }
            //    return Expression.NewArrayInit(conversionType, expressionList);
            //}

            object value = rule.Value.CastTo(conversionType);
            return Expression.Constant(value, conversionType);
        }
        #endregion

        #region "构建筛选条件组"
        /// <summary>
        /// 构建筛选条件组
        /// </summary>
        /// <param name="group">筛选条件组</param>
        /// <returns>筛选条件组</returns>
        /// <exception cref="Exception"></exception>
        protected virtual FilterGroup BuildFilterGroup(FilterGroup group)
        {
            if (group == null || (group.Rules.Count == 0 && group.Groups.Count == 0))
            {
                return group;
            }

            if (group?.Rules?.Count > 0)
            {
                //var removedRules = new List<FilterRule>();
                var addedRules = new List<FilterRule>();
                var addedGroups = new List<FilterGroup>();
                foreach (var rule in group.Rules)
                {
                    //removedRules.AddIfNotExist(rule);
                    var filter = BuildFilterRule(rule);
                    if (filter != null)
                    {
                        if (filter is FilterRule filterRule)
                        {
                            addedRules.AddIfNotExist(filterRule);
                        }
                        else if (filter is FilterGroup filterGroup)
                        {
                            addedGroups.AddIfNotExist(filterGroup);
                        }
                    }
                }
                group.Rules.Clear();
                foreach (var addedRule in addedRules)
                {
                    group.Rules.Add(addedRule);
                }
                foreach (var addedGroup in addedGroups)
                {
                    group.Groups.Add(addedGroup);
                }
            }
            if (group?.Groups?.Count > 0)
            {
                foreach (var subGroup in group.Groups)
                {
                    BuildFilterGroup(subGroup);
                }
            }

            return group;
        }
        #endregion
        #region "构建筛选条件"
        /// <summary>
        /// 构建筛选条件
        /// </summary>
        /// <param name="rule">筛选条件</param>
        /// <returns>筛选条件组</returns>
        /// <exception cref="Exception"></exception>
        protected virtual object BuildFilterRule(FilterRule rule)
        {
            if (rule == null)
            {
                return rule;
            }

            var ruleValue = rule.Value?.ToString();
            // TODO: 将UserFlag之类的功能提升为接口进行服务注册，好方便实现自定义XXXFlag
            if (ruleValue == UserFlagAttribute.CurrentToken)
            {
                // TODO：处理当前用户筛选逻辑
                if (rule.Operate != FilterOperate.Equal)
                {
                    throw new Exception(I18N.T("{0} 只能用在 {1} 操作中", ruleValue, FilterOperate.Equal.ToDescription()));
                }
                ClaimsPrincipal user = CurrentUser;
                if (user == null || !user.Identity.IsAuthenticated)
                {
                    throw new Exception(I18N.T("需要获取当前用户编号，但当前用户为空，可能未登录或已过期。"));
                }
                rule.Value = user.Identity.GetUserId();
                return rule;
            }
            else if (ruleValue == OrganizationFlagAttribute.CurrentToken
                || ruleValue == OrganizationFlagAttribute.CurrentChildrenToken
                || ruleValue == OrganizationFlagAttribute.CurrentParentToken
                || ruleValue == OrganizationFlagAttribute.CurrentParentChildrenToken
                || ruleValue == OrganizationFlagAttribute.ChildrenToken
                || ruleValue == OrganizationFlagAttribute.ParentToken
                || ruleValue == OrganizationFlagAttribute.ParentChildrenToken
                || ruleValue == DepartmentFlagAttribute.CurrentToken
                || ruleValue == DepartmentFlagAttribute.CurrentChildrenToken
                || ruleValue == DepartmentFlagAttribute.CurrentParentToken
                || ruleValue == DepartmentFlagAttribute.CurrentParentChildrenToken
                || ruleValue == DepartmentFlagAttribute.ChildrenToken
                || ruleValue == DepartmentFlagAttribute.ParentToken
                || ruleValue == DepartmentFlagAttribute.ParentChildrenToken)
            {
                // TODO：处理当前组织筛选逻辑
                if (rule.Operate != FilterOperate.Equal)
                {
                    throw new Exception(I18N.T("{0} 只能用在 {1} 操作中", ruleValue, FilterOperate.Equal.ToDescription()));
                }

                var isOrganizationFlag = ruleValue == OrganizationFlagAttribute.CurrentToken
                  || ruleValue == OrganizationFlagAttribute.CurrentChildrenToken
                  || ruleValue == OrganizationFlagAttribute.CurrentParentToken
                  || ruleValue == OrganizationFlagAttribute.CurrentParentChildrenToken
                  || ruleValue == OrganizationFlagAttribute.ChildrenToken
                  || ruleValue == OrganizationFlagAttribute.ParentToken
                  || ruleValue == OrganizationFlagAttribute.ParentChildrenToken;
                //var isDepartmentFlag = ruleValue == DepartmentFlagAttribute.CurrentToken
                //    || ruleValue == DepartmentFlagAttribute.CurrentChildrenToken
                //    || ruleValue == DepartmentFlagAttribute.CurrentParentToken
                //    || ruleValue == DepartmentFlagAttribute.CurrentParentChildrenToken
                //    || ruleValue == DepartmentFlagAttribute.ChildrenToken
                //    || ruleValue == DepartmentFlagAttribute.ParentToken
                //    || ruleValue == DepartmentFlagAttribute.ParentChildrenToken;

                var currentOrganizationId = CurrentOrganizationId;
                var currentDepartmentId = CurrentDepartmentId;
                var organizationId = isOrganizationFlag ? currentOrganizationId : currentDepartmentId;
                if (organizationId.IsMissing())
                {
                    if (isOrganizationFlag)
                    {
                        throw new Exception(I18N.T("需要获取当前用户组织，但当前用户未登录组织。"));
                    }
                    else
                    {
                        throw new Exception(I18N.T("需要获取当前用户部门，但当前用户未登录部门。"));
                    }
                }

                FilterGroup filterGroup = new(FilterOperate.Or);

                var organizationProvider = OrganizationProvider;
                OrganizationDtoSimple[] childDtos = Array.Empty<OrganizationDtoSimple>();
                OrganizationDtoSimple[] parentDtos = Array.Empty<OrganizationDtoSimple>();

                var currentToken = ruleValue == OrganizationFlagAttribute.CurrentToken || ruleValue == DepartmentFlagAttribute.CurrentToken;
                var currentChildrenToken = ruleValue == OrganizationFlagAttribute.CurrentChildrenToken || ruleValue == DepartmentFlagAttribute.CurrentChildrenToken;
                var currentParentToken = ruleValue == OrganizationFlagAttribute.CurrentParentToken || ruleValue == DepartmentFlagAttribute.CurrentParentToken;
                var currentParentChildrenToken = ruleValue == OrganizationFlagAttribute.CurrentParentChildrenToken || ruleValue == DepartmentFlagAttribute.CurrentParentChildrenToken;
                var childrenToken = ruleValue == OrganizationFlagAttribute.ChildrenToken || ruleValue == DepartmentFlagAttribute.ChildrenToken;
                var parentToken = ruleValue == OrganizationFlagAttribute.ParentToken || ruleValue == DepartmentFlagAttribute.ParentToken;
                var parentChildrenToken = ruleValue == OrganizationFlagAttribute.ParentChildrenToken || ruleValue == DepartmentFlagAttribute.ParentChildrenToken;

                if (currentToken || currentChildrenToken || currentParentToken || currentParentChildrenToken)
                {
                    //TODO：处理当前组织机构筛选逻辑
                    filterGroup.AddRule(new FilterRule(rule.Field, organizationId, rule.Operate));
                }
                if (currentChildrenToken || childrenToken)
                {
                    //TODO：处理下级组织机构筛选逻辑
                    childDtos = organizationProvider.GetChildOrganizations(organizationId);
                }
                if (currentParentToken || parentToken)
                {
                    //TODO：处理上级组织机构筛选逻辑
                    parentDtos = organizationProvider.GetParentOrganizations(organizationId);
                }
                if (currentParentChildrenToken || parentChildrenToken)
                {
                    //TODO：处理上下级组织机构筛选逻辑
                    childDtos = organizationProvider.GetChildOrganizations(organizationId);
                    parentDtos = organizationProvider.GetParentOrganizations(organizationId);
                }
                //TODO：处理上下级组织机构筛选逻辑
                if (childDtos != null && childDtos.Length > 0)
                {
                    foreach (var dto in childDtos)
                    {
                        //TODO：处理下级组织机构筛选逻辑
                        filterGroup.AddRule(new FilterRule(rule.Field, dto.Id, rule.Operate));
                    }
                }
                if (parentDtos != null && parentDtos.Length > 0)
                {
                    foreach (var dto in parentDtos)
                    {
                        //TODO：处理上级组织机构筛选逻辑
                        filterGroup.AddRule(new FilterRule(rule.Field, dto.Id, rule.Operate));
                    }
                }

                return filterGroup;
            }
            return rule;
        }
        #endregion

        #endregion

    }

}
